package leetcode.code1139;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	// (i,j) (i,j+k-1)
	// (i+k-1,j) (i+k-1,j+k-1)
	public int largest1BorderedSquare(int[][] grid) {
		int m = grid.length, n = grid[0].length;
		int[][] arr1 = new int[m + 1][n + 1];// 行之间
		int[][] arr2 = new int[m + 1][n + 1];// 列之间
		for (int i = 1; i <= m; i++) {
			for (int j = 1; j <= n; j++) {
				int cur = grid[i - 1][j - 1];
				arr1[i][j] = arr1[i - 1][j] + cur;
				arr2[i][j] = arr2[i][j - 1] + cur;
			}
		}
		int max = 0;
		for (int i = 0; i < m && i + max - 1 < m; i++) {
			for (int j = 0; j < n && j + max - 1 < n; j++) {
				int cur = grid[i][j];
				if (cur == 1) {
					for (int k = Math.max(1, max); k <= Math.min(m, n) && i + k <= m && j + k <= n; k++) {
						if (grid[i][j + k - 1] == 1 
							&& grid[i + k - 1][j] == 1 
							&& grid[i + k - 1][j + k - 1] == 1
							&& arr2[i + 1][j + k] - arr2[i + 1][j] == k 
							&& arr1[i + k][j + 1] - arr1[i][j + 1] == k
							&& arr1[i + k][j + k] - arr1[i][j + k] == k
							&& arr2[i + k][j + k] - arr2[i + k][j] == k) {
							max = k;
						}
					}
				}
			}
		}
		return max * max;
	}

	@Override
	public void debug4() {
		H.compare(9, this.largest1BorderedSquare(H.str2array1("[[1,1,0],[1,1,1],[1,1,1],[1,1,1]]")));
		H.compare(9, this.largest1BorderedSquare(H.str2array1("[[1,1,1],[1,0,1],[1,1,1]]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
